package com.xingkong.coolweather.util;

import android.text.TextUtils;

import com.xingkong.coolweather.db.CoolWeatherDB;
import com.xingkong.coolweather.model.City;
import com.xingkong.coolweather.model.County;
import com.xingkong.coolweather.model.Province;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by cuiguangfan on 2015/10/21.
 */
public class Utility {
    public synchronized static boolean handleProvincesResponse(CoolWeatherDB coolWeatherDB,String response){
        if(!TextUtils.isEmpty(response)){
            try {
                JSONObject jsonObject=new JSONObject(response);
                JSONArray jsonArray=jsonObject.getJSONArray("result");
                for(int i=0;i<jsonArray.length();i++){
                    JSONObject tempObject=jsonArray.getJSONObject(i);
                    long provinceRowNumber=coolWeatherDB.getExitProvinceRowNumber(tempObject.getString("province"));
                    if(provinceRowNumber==-1){
                        Province province=new Province();
                        province.setProvinceName(tempObject.getString("province"));
                        provinceRowNumber=coolWeatherDB.saveProvince(province);
                    }
                    long cityRowNumber=coolWeatherDB.getExitCityRowNumber(tempObject.getString("City"));
                    if(cityRowNumber==-1){
                        City city=new City();
                        city.setCityName(tempObject.getString("City"));
                        city.setProvinceId((int) provinceRowNumber);
                        cityRowNumber=coolWeatherDB.saveCity(city);
                    }
                    long countyRowNumber=coolWeatherDB.getExitCountyRowNumber(tempObject.getString("district"));
                    if(countyRowNumber==-1){
                        County county=new County();
                        county.setCountyName(tempObject.getString("district"));
                        county.setCityId((int) cityRowNumber);
                        coolWeatherDB.saveCounty(county);
                    }
                }
                return true;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

}
